<template>
	<div class="template_com">
		<sapn style="color: #fff;">
			<!-- {{template_idsClone }} -->
		</sapn>
		<a-checkbox-group v-model:value="checkedList" v-if="sortTemplateList?.length">
			<div class="template_con">
				<div  @click.stop="selectTemplate(template_item, $event)" 
				:style="{filter: isFilter(template_item)}" class="template_item" 
				:class="{'active_item': !use_random_template && checkedList.includes(template_item.templateId)}" 
				v-for="(template_item, template_index) in sortTemplateList" 
				:key="template_index">
					<video :id="'video_player_'+template_index" :src="template_item?.material_url"></video>
					<div class="player_con" >
						<cu-icon @click.stop="previewVideo(template_item)" style="font-size: 40px; cursor: pointer;" type="icon-bofang" />
					</div>
					<div class="message_con">
						<!-- {{ use_random_template }} -->
						<a-checkbox
							v-show="!use_random_template"
							:disabled="use_random_template"
							@change.stop="handleCheckChange"
							class="check_icon"
						    :value="sortTemplateList[template_index].templateId"
							>
						</a-checkbox>
						<div class="duration_text">{{template_item.duration_txt}}</div>
						<div class="tag_con">
							<a-tag style="background-color: rgba(0, 0, 0, .3); border: none; color: #fff;" 
							v-for="(tag_item, tag_index) in template_item.material_tags_txt.filter((item, index)=>index<2)" 
							:key="tag_index">{{tag_item}}</a-tag>
						</div>
						<div class="sence_num" v-if="template_item?.material_number">{{template_item?.material_number}}场景</div>
					</div>
					<div class="operate_con">
						<span>{{template_item.name}}</span>
					</div>
				</div>
			</div>
		</a-checkbox-group>
		<div class="no_data" v-if="!sortTemplateList?.length">
			暂无模板数据
		</div>
		<!-- 预览图片 -->
		<materialPreview :visible="previewVisible" :materialDetail="currentMaterial" @close="closePreview" />
	</div>
</template>

<script>
	import {defineComponent, ref, reactive, toRefs, nextTick, computed, watch} from 'vue';
	import request from "../../../../../../common/utils/request";
	import materialPreview from '../../sourceMaterial/modules/materialPreview.vue';
	import {
	} from "@ant-design/icons-vue";
	import store from "@/store";
	let initData = []
	export default defineComponent({
		emits: ['updateNumber'],
		components: {
			materialPreview
		},
		setup(props, context) {
			const state = reactive({
				templateList: [],
				previewVisible: false,
				currentMaterial: {},
				checkedList: [],
				// 克隆数据, 用于切换随机模板数据回显
				checkedListClone: [],
				template_idsClone:[]
			})
			// 是否开启随机模板
			const use_random_template = computed(()=> store.getters.clipJSON.use_random_template)
			
			// 计算属性, 用于获取仓库中已选择的素材数据
			const Store_resource_data = computed(()=>store.getters.clipJSON.resource_data)

			// 排序后的templateList数组 - 将开启随机模板后, 符合条件的模板数据展示在最前面
			const sortTemplateList = computed(()=>{
				console.log('计算属性执行');
				return state.templateList.sort((a, b) => {
					return a.material_number - b.material_number
  			});

			})

			// 筛选符合条件的素材数据
			const filterTemplateList = computed(()=>{
				
				let arr
				if(use_random_template.value){
					arr = sortTemplateList.value.filter(item =>{
					    return Store_resource_data.value[0]?.video.length >= item?.material_number
					})
				}else{
				arr = []
				}
				console.log('筛选执行', arr);
				return arr
			})
			

			const getTemplateList = () => {
				request.get('/work_ai', '/user/shotstack/clip/videoTemplate/list').then(res=> {
					state.templateList = res.lists
					initData = res.lists
					nextTick(()=> {
						state.templateList.map((item, index)=> {
							let dom = document.getElementById('video_player_'+index)
							dom.currentTime = 12
						})
					})
				})
			}
			getTemplateList()
			
			const previewVideo = (item) => {
				state.currentMaterial['material_type'] = 'video'
				state.currentMaterial['material_name'] = item.name
				Object.assign(state.currentMaterial, item)
				state.previewVisible = true
			}
			
			const closePreview = () => {
				state.currentMaterial = {}
				state.previewVisible = false
			}

			// 判断 模板每一项是否添加遮罩
			const isFilter = (item)=>{
				// 未开启随机模板, 不可添加遮罩
				console.log('执行了函数',use_random_template.value );
				if(!use_random_template.value){
					return ''
				// 满足条件 不添加遮罩 
				}else if(use_random_template.value && item?.material_number <= Store_resource_data.value[0].video.length){
					return ''
				// 不满足条件 添加遮罩
				}else{
					return 'brightness(50%)'
				}
			}

			// 选择模板 - 点击复选框
			const handleCheckChange = (value) => {
				console.log('1111111111111111111111111',value);
				state.template_idsClone = state.templateList.filter(item=>state.checkedList.includes(item.templateId))
					store.dispatch('SetClipInfo', {
						template_ids: state.templateList.filter(item=>state.checkedList.includes(item.templateId))
					})
				
					context.emit('updateNumber', {
						type: 'template',
						count: state.checkedList?.length
					})
			}

			// 选择模板 - 点击父级容器
			const selectTemplate  = (item,event)=>{
				// 开启随机模板, 不可选择
				if(use_random_template.value) return
				// 获取事件目标元素
				const target = event.target;
				// 检查目标元素如果是input 则取消事件(input的change 事件会修改当前选中的元素)
				if (target.matches('.ss-checkbox-input[type="checkbox"]')) {
				console.log("点击了指定的checkbox！");
				return 
				}
				// 未开启随机模板, 可以选择, 否则无法选择
				let index = state.checkedList.findIndex(ele => ele == item.templateId)
				if(index !== -1){
				state.checkedList.splice(index, 1)
				handleCheckChange()
				}else{
					state.checkedList.push(item.templateId)
					handleCheckChange()
				}
			}

			// 侦听是否开启随机模板
			watch(()=>use_random_template.value, val=> {
				
				if(val){
					state.checkedListClone = JSON.parse(JSON.stringify(state.checkedList))
					// state.template_idsClone =  JSON.parse(JSON.stringify(store.getters.clipJSON.template_ids))

					state.checkedList = []
					// 使用高亮 符合条件的项 作为选中项
					store.dispatch('SetClipInfo', {
						template_ids:  filterTemplateList.value
					})
					context.emit('updateNumber', {
						type: 'template',
						count: filterTemplateList.value.length
					})
				}else{
					if(state.checkedListClone.length){
						state.checkedList = JSON.parse(JSON.stringify(state.checkedListClone))
						store.dispatch('SetClipInfo', {
						template_ids:  JSON.parse(JSON.stringify(state.template_idsClone))
					})
					}else{

					}
				}
				console.log(state.template_idsClone,'state.template_idsClone');
			},
			{
				immediate: true
			}
				)

			// 开启随机模板并且当前有数据
			watch(()=>filterTemplateList.value, val=> {
				if(use_random_template.value && val.length){
					// 使用高亮 符合条件的项 作为选中项
					store.dispatch('SetClipInfo', {
						template_ids:  val
					})
					context.emit('updateNumber', {
						type: 'template',
						count:val.length
					})
				}else if(use_random_template.value && !val.length){
					store.dispatch('SetClipInfo', {
						template_ids:  []
					})
					context.emit('updateNumber', {
						type: 'template',
						count:0
					})

				}
				console.log('watch触发', val, store.getters.clipJSON);
			},)




			
			watch(
				() => store.getters.selectTemplate,
				(val) => {
					let arr = []
					if(val.labelKey != 0){
						arr = initData.filter(item=>item?.material_tags_txt.includes(val.label))
					} else {
						arr = initData
					}
					if(val.durationKey != 0){
						if(val.durationKey == 1){
							arr = arr.filter(item=>item.material_duration<10)
						} else if(val.durationKey == 2){
							arr = arr.filter(item=>item.material_duration>=10 && item.material_duration<15)
						} else {
							arr = arr.filter(item=>item.material_duration>=15)
						}
					} else {
						if(val.labelKey != 0){
							arr = initData.filter(item=>item?.material_tags_txt.includes(val.label))
						} else {
							arr = initData
						}
					}
					state.templateList = arr
					nextTick(()=> {
						state.templateList.map((item, index)=> {
							let dom = document.getElementById('video_player_'+index)
							dom.currentTime = 12
						})
					})
				}, {
					immediate: true,
					deep: true
				}
			);
			
			// watch(()=>store.getters.clipJSON.template_ids, val=> {
			// 	if(val && val?.length){
			// 		state.checkedList = val.map(i=>i.id)
			// 		context.emit('updateNumber', {
			// 			type: 'template',
			// 			count: state.checkedList?.length
			// 		})
			// 	}
			// }, {
			// 	deep: true,
			// 	immediate: true
			// })
			
			return {
				...toRefs(state),
				handleCheckChange,
				previewVideo,
				closePreview,
				selectTemplate,
				isFilter,
				use_random_template,
				Store_resource_data,
				sortTemplateList,
				filterTemplateList
				
			}
		}
	})
</script>

<style lang="less" scoped>
	@width: 120px;
	@height: 213.33px;
	.template_com{
	.templateItem{
	}
		.no_data{
			width: 100%;
			height: 285px;
			color: #fff;
			display: flex;
			align-items: center;
			justify-content: center;
		}
		.template_con{
			display: flex;
			align-items: center;
			flex-wrap: wrap;
			.active_item{
					border-color: #2878FF !important
				}
			.template_item{
				box-sizing: content-box;
				cursor: pointer;
				border-radius: 0px;
				border: 1px solid #fff;
				width: @width;
				min-height: @height;
				background-color: #000;
				margin-top: 30px;
				margin-left: 10px;
				display: flex;
				align-items: center;
				justify-content: center;
				color: #fff;
				background-position: center;
				background-repeat: no-repeat;
				background-size: 100% 100%;
				position: relative;
				overflow: hidden;
				
				video{
					max-width: @width;
					max-height: @height;
				}
				
				&:hover{
					.player_con{
						display: flex;
						align-items: center;
						justify-content: center;
					}
				}
				
				.player_con{
					position: absolute;
					left: 0;
					top: 0;
					width: @width;
					height: @height;
					display: none;
					background-color: rgba(0, 0, 0, .3);
					z-index: 9;
				}
				
				.message_con{
					position: absolute;
					left: 0;
					top: 0;
					width: @width;
					height: @height;
					
					.sence_num{
						position: absolute;
						left: 0px;
						bottom: 0px;
						background-color: rgba(0, 0, 0, .6);
						padding: 2px 6px;
						border-top-right-radius: 10px;
						display: flex;
						align-items: center;
						justify-content: center;
						font-size: 12px;
					}
					
					.tag_con{
						position: absolute;
						left: 5px;
						top: 10px;
						width: 100%;
						flex-wrap: wrap;
					}
					
					.duration_text{
						position: absolute;
						right: 5px;
						bottom: 5px;
						padding: 1px 5px;
						background-color: rgba(0, 0, 0, .3);
						border-radius: 20px;
						font-size: 12px;
					}
					.check_icon{
						position: absolute;
						right: 10px;
						top: 10px;
						z-index: 10;
					}
				}
				
				.operate_con{
					position: absolute;
					width: 100%;
					height: 35px;
					line-height: 35px;
					left: 0;
					bottom: -35px;
					display: inline-block;
					white-space: nowrap;
					overflow: hidden;
					text-overflow: ellipsis;
				}
			}
		}
	}
</style>